package com.richard.library.basic.util;

import android.app.Activity;
import android.app.Presentation;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.Display;

import com.richard.library.context.AppContext;

/**
 * <pre>
 * Description : 副屏工具类
 * Author : admin-richard
 * Date : 2020-02-17 11:09
 * Changelog:
 * Version            Date            Author              Detail
 * ----------------------------------------------------------------------
 * 1.0         2020-02-17 11:09     admin-richard         new file.
 * </pre>
 */
public final class PresentationUtil {

    public static final int REQUEST_OVERLAY = 9999;

    //屏幕管理器
    private DisplayManager mDisplayManager;

    private static final class InstanceHolder {
        static final PresentationUtil instance = new PresentationUtil();
    }

    public static PresentationUtil get() {
        return InstanceHolder.instance;
    }


    /**
     * 获取屏幕管理器
     */
    public DisplayManager getDisplayManager() {
        if (mDisplayManager == null) {
            mDisplayManager = (DisplayManager) AppContext.get().getSystemService(Context.DISPLAY_SERVICE);
        }

        return mDisplayManager;
    }


    /**
     * 获取屏幕数组
     */
    public Display[] getDisplays() {
        return this.getDisplayManager().getDisplays();
    }


    /**
     * 获取指定屏幕
     *
     * @param displayNum 屏幕序号
     */
    public Display getDisplay(int displayNum) {
        Display[] displays = this.getDisplays();
        if (displays == null || displays.length <= displayNum) {
            return null;
        }
        return displays[displayNum];
    }

    /**
     * 显示副屏
     */
    public void show(Presentation presentation) {
        if (presentation == null || presentation.isShowing()) {
            return;
        }
        presentation.show();
    }


    /**
     * 关闭副屏幕
     */
    public void dismiss(Presentation presentation) {
        if (presentation == null || !presentation.isShowing()) {
            return;
        }
        presentation.dismiss();
    }

    /**
     * 6.0以上获取副屏权限
     */
    public void requestOverlayPermission(Context context, IBack iBack) {
        Activity activity = (Activity) context;
        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(context)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + context.getPackageName()));
                activity.startActivityForResult(intent, REQUEST_OVERLAY);
                iBack.onNeedPermission();
            } else {
                iBack.onSuccess();
            }
        } else {
            iBack.onSuccess();
        }
    }

    public interface IBack {

        void onSuccess();

        void onNeedPermission();
    }

}
